package com.jrh.dal;

import java.util.HashMap;
import java.util.Map;

import org.springframework.orm.ibatis.SqlMapClientOperations;

/**
 * DAO基础类
 * 
 * @author jasen.hsu.cn@gmail.com 2012-3-27 下午9:46:39
 */
public class BaseDao<T> {

    protected SqlMapClientOperations sqlMapClientTemplate;
    protected String                 namespace;

    public static final Integer      DEFAULT_DB_PAGE_SIZE = 10;

    public Integer getStartIndex(Integer currentPage, Integer pageSize) {
        if (currentPage == null || currentPage <= 0) {
            currentPage = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = DEFAULT_DB_PAGE_SIZE;
        }
        Integer start = (currentPage - 1) * pageSize;
        return start;
    }

    public Map<String, Object> getNewParamMap() {
        Map<String, Object> map = new HashMap<String, Object>();
        return map;
    }

    public Map<String, Object> getPageMap(Integer start, Integer pageSize) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (start == null || start < 0) {
            start = 0;
        }
        if (pageSize == null || pageSize < 0) {
            pageSize = DEFAULT_DB_PAGE_SIZE;
        }
        map.put("start", start);
        map.put("size", pageSize);
        return map;
    }

    @SuppressWarnings("unchecked")
    public T load(Long id) {
        return (T) sqlMapClientTemplate.queryForObject(namespace + "." + "load", id);
    }

    @SuppressWarnings("unchecked")
    public T load(Long id, String status) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("status", status);
        return (T) sqlMapClientTemplate.queryForObject(namespace + "." + "loadByIdAndStatus", map);
    }

    @SuppressWarnings("unchecked")
    public T lock(Long id) {
        return (T) sqlMapClientTemplate.queryForObject(namespace + "." + "lock", id);
    }

    public boolean update(T entity) {
        return sqlMapClientTemplate.update(namespace + "." + "update", entity) == 1;
    }

    public  void create(T entity) {
        sqlMapClientTemplate.insert(namespace + "." + "create", entity);
    }

    public void delete(Long id) {
        sqlMapClientTemplate.delete(namespace + "." + "delete", id);
    }

    public void setSqlMapClientTemplate(SqlMapClientOperations sqlMapClientTemplate) {
        this.sqlMapClientTemplate = sqlMapClientTemplate;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

}
